package com.guochenglang.www.service.section;

import com.guochenglang.www.service.AffairService;
import com.guochenglang.www.service.anotate.Affair;
import com.guochenglang.www.service.impl.AffairServiceImpl;
import com.guochenglang.www.util.error.MyExceptionHandler;
import com.guochenglang.www.web.result.Result;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Method;

/**
 * @author GuoChenglang
 */
public class LogHandlerSection implements MethodInterceptor {
    private static final Logger LOGGER = LogManager.getLogger(LogHandlerSection.class);
    private static final AffairService AFFAIR_SERVICE = new AffairServiceImpl();

    /**
     * 获得代理对象,统一处理事务，日志，异常
     *
     * @param clazz 要代理的对象
     * @return 代理的对象
     */
    public Object getProxy(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        try {
            Object result = null;
            if (method.isAnnotationPresent(Affair.class)) {
                AFFAIR_SERVICE.startAffair();
                try {
                    result = methodProxy.invokeSuper(o, objects);
                    AFFAIR_SERVICE.commit();
                    return result;
                } catch (Exception e) {
                    AFFAIR_SERVICE.rollback();
                } finally {
                    AFFAIR_SERVICE.returnConnection();
                }
            }
            result = methodProxy.invokeSuper(o, objects);
            return result;
        } catch (Exception e) {
            //记录全局业务异常
            LOGGER.error("发生异常！，异常为：{},异常栈为：", e, e);
            throw e;
        }
    }
}
